/**
 * @(#)HttpUtil.java 1.0.0 2014年10月20日 上午11:45:34
 * <p>
 * Copyright © 2014 善林金融.  All rights reserved.
 */

package com.study.springboot.common.util;

import cn.hutool.core.lang.Assert;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 管理spring工具类
 *
 * @author wei.zhao
 * @date 2021年11月30日 11:26
 */
@Component
public class SpringUtil implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中。
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        Assert.isTrue(null == SpringUtil.applicationContext,
                "SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:",
                SpringUtil.applicationContext);
        SpringUtil.applicationContext = applicationContext;
    }

    /**
     * 获取profile
     */
    public static String getProfile() {
        String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
        if (profiles != null && profiles.length > 0) {
            return profiles[0];
        }
        return null;
    }

    /**
     * 获取环境变量
     */
    public static String getEnvironment(String key) {
        return applicationContext.getEnvironment().getProperty(key);
    }

    /**
     * 从applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从applicationContext中取得Bean, 自动转型为所赋值对象的类型
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 检查ApplicationContext不为空
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null, "applicaitonContext属性未注入！");
    }

    /**
     * 取得存储在静态变量中的ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量
     */
    @Override
    public void destroy() throws Exception {
        applicationContext = null;
    }

}
